package com.iwhalecloud.bss.kite.cucc.service.pos.handler.impl;

import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.common.util.KiteDateUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Date;
import java.util.stream.Collectors;

import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAttrDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import org.springframework.stereotype.Service;

import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferAttrCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.dataservice.entity.OfferAttr;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.dataservice.util.IdUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosPaymentDTO;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.IKitePosSceneHandler;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.KitePosHandlerContext;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.ztesoft.bss.common.util.SpringUtil;

import edu.emory.mathcs.backport.java.util.Arrays;

@Service
public class KitePosPaymentHandler implements IKitePosSceneHandler {

	@Override
	public void handle(KitePosHandlerContext context) {
        KitePosPaymentDTO payment = new KitePosPaymentDTO();
        List<KiteInst> kiteInsts = CuccPosServiceUtils.queryOneOffFees(context.getSceneInstId())
            .stream().filter(additionalOffer -> ActionType.A.name().equals(additionalOffer.getActionType().name()))
            .collect(Collectors.toList());
        if (!kiteInsts.isEmpty()) {
            //销售不修改趸交资费payment节点的内容,已有就沿用
            if (KiteListUtils.isNotEmpty(context.getPosDto().getPayments())) {
                payment = context.getPosDto().getPayments().get(0);
            }
            else {
                this.packageOneOffFeePayments(context, payment, kiteInsts);
            }
        }
        else {
            String instanceId = IdUtils.generateInstId(InstType.MKT_RES_INST);
            //签订任务需要用旧的实例id
            if (KiteListUtils.isNotEmpty(context.getPosDto().getPayments())) {
                instanceId = context.getPosDto().getPayments().get(0).getInstanceId();
            }
            payment.setInstanceId(instanceId);
            payment.setPayType("XCZF");
            payment.setPayWay("XJZF");

            payment.setPayStatus("0");
            //payment.setChangeType("0");

            //this.addInstanceIdAttr(context.getSceneInstId(), "instanceId", instanceId, payment);

            KiteOfferInst mainOfferInst = null;
            IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
            String mainOfferInstId = querySceneInstService.getExtParameterValue(context.getSceneInstId(), "mainOfferInstId");
            if (KiteStringUtils.isEmpty(mainOfferInstId)) {
                mainOfferInst = querySceneInstService.getMainOfferInst(context.getSceneInstId());
            }
            else {
                mainOfferInst = querySceneInstService.getOfferInst(context.getCustId(), mainOfferInstId);
            }

            List<OfferAttr> offerAttrs = OfferAttrCache.get(mainOfferInst.getOfferId());
            String categoryId = Optional.ofNullable(OfferCache.get(mainOfferInst.getOfferId())).map(Offer::getCateId).orElse("");
            List<DcPublic> dcpublic = DcPublicCache.getByPcode("20210305001", "onPayment", categoryId);
            if (KiteListUtils.isNotEmpty(dcpublic)) {
                context.getPosDto().setPayments(Lists.newArrayList());
                return;
            }
            for (OfferAttr offerAttr : offerAttrs) {
                if ("price".equals(offerAttr.getFieldName())) {
                    payment.setAmount((Double.valueOf(Objects.isNull(offerAttr.getDefaultValue()) ? "0" : offerAttr.getDefaultValue()).longValue() * 1000));
                    break;
                }
            }
        }

        context.getPosDto().setPayments(Arrays.asList(new Object[] {payment}));

    }

    private void packageOneOffFeePayments(KitePosHandlerContext context, KitePosPaymentDTO payment, List<KiteInst> oneOffFees) {
        payment.setInstanceId(IdUtils.generateInstId(InstType.MKT_RES_INST));
        payment.setPayType("XCZF");
        payment.setPayWay("XJZF");
        payment.setFeesName("集客专线趸交");
        payment.setPayStatus("0");

        int totalFee = 0;
        for (KiteInst kiteInst : oneOffFees) {
            String oneOffFee = Optional.ofNullable(kiteInst.getAttr("200003241")).map(KiteAttr::getValue).orElse("0");
            totalFee += Integer.parseInt(oneOffFee);
        }
        payment.setAmount(Double.valueOf(totalFee).longValue() * 1000);
        String amountStr = String.valueOf(payment.getAmount());
        Map attrMap = new HashMap();
        attrMap.put("payCost","0");
        attrMap.put("ifPay", "1");
        attrMap.put("printInvoice", "0");
        attrMap.put("payMoney", amountStr);
        attrMap.put("payMount", amountStr);
        List<KitePosAttrDTO> attrList = new ArrayList<>();
        String startDate = KiteDateUtils.formatDate(new Date(), KiteDateUtils.DATE_TIME_FORMAT_14);
        Iterator iterator = attrMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
            KitePosAttrDTO attr = new KitePosAttrDTO();
            attr.setCode(entry.getKey());
            attr.setType("STRING");
            attr.setStartDate(startDate);
            attr.setEndDate(LocalKeyConsts.ATTR_SEND_DATE);
            attr.setValue(entry.getValue());
            attrList.add(attr);
        }
        payment.setAttrs(attrList);
    }
}
